import {fetch} from "./network";
import api from './api';

/**
 * 最左侧： 财政结构和税收结构环状图
 */
export async function getFinancialAndTaxStatus() {
  const { data: { financial = [], tax = [] } = {} } = await fetch(api.getFinancialAndTaxStatus) || {};
  return {
    // 财政
    financial: financial.map(({ rate: value = 0, name = '未知' }) => ({
      value,
      name
    })),
    // 税收
    tax: tax.map(({ rate: value = 0, name = '未知' }) => ({
      value,
      name
    })),
  }
}

/**
 * 最左侧： 分月财政收入趋势和税收趋势 折线区域图
 */
export async function getMonthlyFinancialAndTaxTend() {
  const { data: { financial = [], tax = [] } = {} } = await fetch(api.getMonthlyFinancialAndTaxTend) || {};
  // const current = new Date().getFullYear();
  const current = financial[0].month.split("-")[0];
  // 月份keys
  const months = year => ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']
    .map(month => `${year}-${month}`);
  // 找到内容
  const find = (collection, month) => collection.find(item => item.month === month) || {};
  // 构建数据
  const build = (collection, year, key) => ({
    title: key === 'lastAmount' ? `${year-1}年` : `${year}年`,
    data: months(year).map(month => find(collection, month)[key] || 0).filter((item, index) => index < collection.length).map((v,i,arr) => {
      return key === 'lastAmount' && i != 0 ? v-arr[i-1] : v;
    }),
  });
  // 组合map
  return {
    // 财政
    financial: [
      build(financial, current, 'lastAmount'),
      build(financial, current, 'amount'),
    ],
    // 税收
    tax: [
      build(tax, current, 'lastAmount'),
      build(tax, current, 'amount'),
    ],
  }
}

/**
 * 地图紧邻右侧下方： 一般公共预算支出结构环状图 + 条形图
 */
export async function getPublicOutcomeDetail() {
  // 饼图数据和条形图数据
  const { data = [] } = await fetch(api.getPublicOutcomeDetail) || {};
  // 转换
  return {
    pie: data.map(({ rate: value = 0, name }) => ({ value, name })),
    strip: {
      titles: data.map(({ name }) => name),
      values: data.map(({ amount }) => amount),
    },
  };
}
